package com.baizhi.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baizhi.dao.VideoDao;
import com.baizhi.entity.User;
import com.baizhi.entity.Video;
import com.baizhi.util.AliYun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


@Service
@Transactional
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoDao videoDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Map<String, Object> queryByPage(int page, int size) {
        Map<String,Object> map = new HashMap<>();

        List<Video> list = videoDao.queryByPage((page - 1) * size, size);
        //分页查的数据
        map.put("data",list);

        //存储当前数据
        map.put("page",page);

        //存储总页数    总条数 / 每页显示的条数  = 页数
        int countNum = videoDao.queryCount();  //总条数
        //总页数
        int pageNum = countNum%size == 0?countNum/size:countNum/size+1;
        map.put("pageNum",pageNum);
        return map;
    }

    @Override
    public void add(MultipartFile file,Video video) {
//        videoDao.add(video);
        //1.将视频上传阿里云
        //2.视频截取第一帧   设置时间限制
        //3.将视频第一帧保存至阿里云
        //4.数据入库

        long time = new Date().getTime();
        String fileName = time+file.getOriginalFilename();
        AliYun.uploadByBytes(file,"video/"+fileName);
        //将视频截帧  设置时间限制
        String s = AliYun.jqVideo("video/"+fileName);
        //将视频第一帧保存到阿里云中
        int i = fileName.lastIndexOf('.');
        String substring = fileName.substring(0, i);
        AliYun.URLupload(s,substring+".jpg");

        //数据入库
        video.setId(UUID.randomUUID().toString());
        video.setCoverPath("http://2017class.oss-cn-beijing.aliyuncs.com/videoImg/"+substring+".jpg"); //封面路径
        video.setCreateDate(new Date()); //创建时间
        video.setUser(new User("1",null,null,null,null,null,null,null,null));
        video.setVideoPath("http://2017class.oss-cn-beijing.aliyuncs.com/video/"+fileName);
        videoDao.add(video);
    }

    @Override
    public void delete(String id,String videoPath,String coverPath) {

        //封面的路径
        String substring = coverPath.substring(coverPath.lastIndexOf("/") + 1);  //截取路径
        AliYun.delete("videoImg/"+substring);  //拼接路径

        //视频的路径
        String substring1 = videoPath.substring(videoPath.lastIndexOf("/") + 1);
        System.out.println(substring1);
        AliYun.delete("video/"+substring1);

        videoDao.delete(id);
    }

}
